package logic

import (
	"book/bookrpc/bookrpc"
	"book/bookrpc/internal/svc"
	"book/models/cache"
	"book/models/mysql"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"math/rand"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *bookrpc.RegisterRequest) (*bookrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.RDB.Get(l.ctx, "captcha"+in.Account).Result()

	if in.CaptchaCode != result {
		return nil, fmt.Errorf("验证码错误请重新输入")
	}

	result1, _ := cache.RDB.Get(l.ctx, "sendSms"+in.Account).Result()

	if in.SmsCode != result1 {
		return nil, fmt.Errorf("短信验证码错误请重新输入")
	}

	var findUser mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&findUser)

	if findUser.ID != 0 {
		return nil, fmt.Errorf("当前账号已被注册,请更换账号")
	}

	//%s 填充字符串
	//%d 填充整形
	//%f 填充浮点型
	//%c 填充字节
	//%T 输出类型

	user := mysql.User{
		Account:  in.Account,
		Password: in.Password,
		Name:     fmt.Sprintf("%s_%d", "游客", rand.Intn(100000)),
		Image:    "https://ts1.tc.mm.bing.net/th/id/OIP-C.rPQTtL06uTRQSkiUvIGykwAAAA?w=205&h=211&c=8&rs=1&qlt=90&o=6&cb=thwsc4&pid=3.1&rm=2",
	}
	mysql.DB.Debug().Create(&user)

	return &bookrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
